<?php
namespace App\Controllers\Home;
use App\Libs\Home\Home as libHome;
use App\Models\Home\Home;
use App\Models\Home\Prize;
use \App\Libs\Cache\Redis;
use \App\Models\Home\User;
/**
*	获取抽奖
*/
class Choujiang extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        //$this->needLogin = TRUE;
    }
	
	public function execute(){
		$key = '';
		if (isset($_COOKIE[SESSION_KEY_OPEN]) && ! empty($_COOKIE[SESSION_KEY_OPEN])) {
            $key = trim($_COOKIE[SESSION_KEY_OPEN]);
		}
		$openid = \App\Libs\Cache\Redis::get(trim($key));
		if( empty( $openid ) ){
				return \App\Libs\Views\Json::view(1, '授权失败，请退出重新进入', null);	
		}
		$user = User::find(array(
			' openid = :openid:',
			'bind'=>array( 'openid'=>$openid )
		));
		if( empty( $user ) ){
			return \App\Libs\Views\Json::view(1, '授权用户不存在，请退出重新进入', null);	
		}
		$is_user = $user->is_user;
		if( empty( $is_user ) ){
			return \App\Libs\Views\Json::view(1, '未选择是哪款大牌，请重新进入选择', null);	
		}
		
		//判断抽奖次数
		$count = Redis::get('choujiang'.date('Ymd').$openid);
		if( empty( $count ) ){
			$count = 1;
		}else{
			if( $count >= 3 ){
				return \App\Libs\Views\Json::view(1, '一天只能抽三次奖', null);	
			}
			$count += 1;
		}
		
		//如果用户中了1次奖。就不在中奖
		/*$count = Home::count(array(
			' openid = :openid:',
			'bind'=>array( 'openid'=>$openid )
		));
		if( $count >= 1 ){
			return \App\Libs\Views\Json::view(2, '抽奖成功', self::jiangpin($is_user , 4 ));	
			//return array('id'=>4,'name'=>'谢谢参与');
		}*/
		
		//查询所有奖品
		$prize = Prize::findAll(array(
			' is_user = :is_user:',
			'bind'=>array( 'is_user'=>$is_user )
		))->toArray();
		$prizeCount = 0;
		foreach( $prize as $k =>$v ){
			$proArr[$k]['id'] = $v['prize'];
			$proArr[$k]['v'] = $v['count'];
			$proArr[$k]['name'] = $v['name'];
			$prizeCount += $v['count'];
		}
		//$proArr[4] = array('id'=>'4','谢谢参与','v'=>(10000 - $prizeCount) ); //暂时不加上这个
		//print_r( $proArr );
		
		$jiangpin = self::choujiangInfo( $proArr ,$is_user,$openid);
		$params = array(
			'openid' => $openid,
			'ctime' => date('Y-m-d'),
			'is_get' => 0,
			'jiang' => $jiangpin['id'],
			'is_user' => $is_user
		);
		
		$id = libHome::addChoujiang( $params);
		if( !empty( $id ) ){
			//如果不等于4 
			if(  $jiangpin['id'] != 4 ){
				//减奖品值
				$prizeInfo = Prize::find(array(
					'is_user = :is_user: and prize = :prize: ',
					'bind' => array( 'is_user' => $is_user , 'prize' => $jiangpin['id'] )
				));
				$prizeInfo->count -= 1;
				$prizeInfo->save();
			}
			//一个用户一天只能抽3次
			Redis::setex('choujiang'.date('Ymd').$openid, 24*60*60 , $count );
			return \App\Libs\Views\Json::view(0, '抽奖成功', self::jiangpin($is_user , $jiangpin['id']));	
		}else{
			return \App\Libs\Views\Json::view(1, '抽奖失败', null);	
		}
		
		
	}
	
	/**
	*	抽奖算法
	*$is_user是什么用户
	*/
	public static function choujiangInfo($proArr , $is_user,$openid){ 
		$result = array();
		foreach ($proArr as $key => $val) {
			$arr[$key] = $val['v']; 
		} 
		// 概率数组的总概率  
		$proSum = array_sum($arr);        
		asort($arr);
		// 概率数组循环   
		foreach ($arr as $k => $v) {   
			$randNum = mt_rand(1, $proSum);   
			if ($randNum <= $v) {   
				$result = $proArr[$k];   
				break;   
			} else {   
				$proSum -= $v;   
			}         
		}
		
		//如果用户这次的奖已经中过了。不能中重复的奖
		/*$home = Home::find(array(
			' jiang = :jiang: and is_user = :isuser:',
			'bind'=>array( 'jiang'=>$v['id'] , 'isuser'=>$is_user)
		));
		if( !empty( $home ) ){
			self::choujiangInfo( $is_user );
		}*/
		
		return $result;  
	}
	
	public static function jiangpin( $userIndex , $jiangIndex  ){
		$arr = array(
			'1' => array(
				'1' => array( 'name'=>'冰神卡免费体验一个月','type'=>'link','label'=>'1'),
				'2' => array( 'name'=>'优酷会员30天','type'=>'link','label'=>'6'),
				'3' => array( 'name'=>'哈罗单车免费骑','type'=>'link','label'=>'3'),
				'4' => array( 'name'=>'谢谢参与','type'=>'link','label'=>'4')
			),
			'2' => array(
				'1' => array( 'name'=>'100元红包电子券','type'=>'phone','label'=>'5'),
				'2' => array( 'name'=>'爱奇艺会员7天体验','type'=>'phone','label'=>'2'),
				'3' => array( 'name'=>'哈罗单车免费骑','type'=>'link','label'=>'7'),
				'4' => array( 'name'=>'谢谢参与','type'=>'link','label'=>'4')
			)
		);
		return $arr[$userIndex][$jiangIndex];
		
	}
}
